package servlet;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.http.*;

import dbOperator.*;

public class Login extends HttpServlet{

	/**
	 * 
	 */
	private static final long serialVersionUID = -4143721484509460L;

    /**这个函数识别登录用户的身份，然后定向到不同的主页
	 * @param request 客户端的请求
	 * @param response 给客户端的响应
	 * @throws IOException
     * makisemirai注释
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
		Cookie cookies[] = request.getCookies();
		if(cookies == null) {response.sendRedirect("index.html");return;}
		for(Cookie c : cookies) {
			if(c.getName().equals("LoginInfo")) {
				String currentCookie = c.getValue();
				try {
					int uid = AdvancedOperation.getUidbyCookie(currentCookie);
						int userIdentity = AdvancedOperation.getIdentity(uid);
						HttpSession session = request.getSession();
						session.setAttribute("uid", uid);
						session.setAttribute("userIdentity", userIdentity);
						switch(userIdentity) {
						case 1:{response.sendRedirect("admin.jsp");break;}
						case 2:{response.sendRedirect("librarian.jsp");break;}
						case 3:{response.sendRedirect("reader.html");break;}
						default:{response.sendRedirect("index.html");break;}
					}
				} catch (SQLException e) {
					// TODO 自动生成的 catch 块
					e.printStackTrace();
				}
			}
		}
		return;
	}
	
    /**这个函数用于判断用户的信息、密码是否正确输入，正确则打印出用户的登录信息并储存，若不正确则提示并返回登录界面
	 * @param request 客户端的请求
	 * @param response 给客户端的响应
	 * @throws IOException
     * makisemirai注释
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String information = (String) request.getParameter("info");
		String password = dataOperator.BasicOperation.MD5((String) request.getParameter("pwd"));
		String currentCookie = null;
		try {
			currentCookie = AdvancedOperation.getLoginInfo(information, password);
			System.out.println(currentCookie);
		} catch (SQLException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
		if(currentCookie != null) {
			Cookie loginInfo = new Cookie("LoginInfo",currentCookie);
			loginInfo.setMaxAge(604800);
			//604800 = 60*60*24*7 ，即cookie的有效期为7天
			response.addCookie(loginInfo);
			response.sendRedirect("launch");
			return;
		}
		else {
			//在此加入弹窗提示密码错误的代码，并重新定位到登录页面
			response.sendRedirect("index.html");
			return;
		}
	}
}
